package net.gz01.wallet.web.controller.admin;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOIDGenerate;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.Channel;
import net.gz01.wallet.web.model.Dictionary;
import net.gz01.wallet.web.model.FeeModel;
import net.gz01.wallet.web.model.RiskRule;
import net.gz01.wallet.web.model.TradeConfig;

public class TradeConfigController extends BaseController {

	public void search() {
		render("basedata/tradeConfigList.html");
	}

	public void listJson() {
		ZOSearchCondition sc = super.getSearchCondition();
		Page<TradeConfig> pageResult = TradeConfig.dao.search(sc);
		renderJson(new PageRespon(pageResult));
	}

	public void addPage() {
		setAttr("feeList", FeeModel.dao.selectAll());
		setAttr("channelList", Channel.dao.selectAll());
		setAttr("riskRuleList", RiskRule.dao.selectAll());
		setAttr("bizTypeList", Dictionary.dao.selectBizType());
		render("basedata/tradeConfigAdd.html");
	}

	public void updatePage() {
		TradeConfig tradeConfig = TradeConfig.dao.findById(getPara("id"));
		setAttr("feeList", FeeModel.dao.selectAll());
		setAttr("channelList", Channel.dao.selectAll());
		setAttr("riskRuleList", RiskRule.dao.selectAll());
		setAttr("bizTypeList", Dictionary.dao.selectBizType());
		setAttr("tradeConfig", tradeConfig);
		render("basedata/tradeConfigUpdate.html");
	}

	@Before(Tx.class)
	public void add() {
		TradeConfig item = getModel(TradeConfig.class, true);
		TradeConfig tmp = TradeConfig.dao.select(item.getMerchCode(), item.getBizType());
		if (StrKit.isBlank(item.getChannelCode())) {
			renderFail("请选择渠道");
			return;
		}
		if (StrKit.isBlank(item.getBizType())) {
			renderFail("请选择类型");
			return;
		}
		if (item.getFeeId() == null) {
			renderFail("请选择费率");
			return;
		}
		if (item.getRiskRuleId() == null) {
			renderFail("请选择风控规则");
			return;
		}
		if (tmp != null) {
			renderFail("该商户已经配置了此支付类别，不能重复配置");
		} else {
			item.setId(ZOIDGenerate.getUUID());
			item.save();
			renderSuccess();
		}
	}

	public void update() {
		TradeConfig item = getModel(TradeConfig.class, true);
		if (StrKit.isBlank(item.getChannelCode())) {
			renderFail("请选择渠道");
			return;
		}
		if (StrKit.isBlank(item.getBizType())) {
			renderFail("请选择类型");
			return;
		}
		if (item.getFeeId() == null) {
			renderFail("请选择费率");
			return;
		}
		if (item.getRiskRuleId() == null) {
			renderFail("请选择风控规则");
			return;
		}
		item.update();
		renderSuccess();
	}

	public void delete() {
		TradeConfig.dao.deleteById(getPara("id"));
		renderSuccess(false);
	}

}

